package com.zuul2;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;

public class Myfilter extends ZuulFilter {
    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {

        RequestContext cxt = RequestContext.getCurrentContext();
        System.out.println("cxt="+cxt);
        //从当前上下文对象获得当前请求
        HttpServletRequest request = cxt.getRequest();
        System.out.println("request="+request);
        HttpServletResponse response = cxt.getResponse();
        System.out.println("response="+response);

        String loginoutFlag=request.getRequestURI();
        System.out.println("test="+loginoutFlag);
        if(loginoutFlag != null && "/login/selectuser".equals(loginoutFlag)){
            System.out.println("放行");
            return false ;
        }else{
            if("/finance/".equals(request.getRequestURI().substring(0,9))||"/order/".equals(request.getRequestURI().substring(0,7))||
                    "/wares/".equals(request.getRequestURI().substring(0,7)) ||"/purchase/".equals(request.getRequestURI().substring(0,10))||
                    "/login/del".equals(request.getRequestURI())){
                System.out.println("allnews 拦截");
                return true;
            }else{
                return false;
            }
//            if("/finance/".equals(request.getRequestURI().substring(0,9))||"/login/del".equals(request.getRequestURI())){
//                System.out.println("allnews 拦截");
//                return true;
//            }else{
//                return false;
//            }
//            return false;
        }
    }

    @Override
    public Object run() throws ZuulException {
       //前台获取key 以及value
        //获取zuul提供的请求上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext() ;
        //从上下文中获取request对象
        HttpServletRequest request = requestContext.getRequest() ;
        //从request中获取session对象
//        HttpSession session = request.getSession() ;
        //从上下文中获取response对象
        HttpServletResponse response = requestContext.getResponse() ;

//        String key=redisTemplate.opsForValue().get();
        RequestContext cxt=RequestContext.getCurrentContext();
//        HttpServletRequest request=cxt.getRequest();
        System.out.println("token="+CookieUtils.getCookieByName(request, "token"));

        if ("/login/del".equals(request.getRequestURI())){
            if( null!= CookieUtils.getCookieByName(request, "token")){
                Cookie cookie = CookieUtils.getCookieByName(request, "token");
                String key=cookie.getValue().substring(0,cookie.getValue().indexOf("|"));
                redisTemplate.delete(key);
                return null;
            }
        }

        if( CookieUtils.getCookieByName(request, "token")==null){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            try {
                response.getWriter().write("<h1>请登录后使用！</h1><button><a href=''>去登录</a></button>");
            } catch (IOException e) {
                e.printStackTrace();
            }
            cxt.setResponseStatusCode(433);
            cxt.setSendZuulResponse(false);
            System.out.println("进来了1433");

        }else {
            Cookie cookie = CookieUtils.getCookieByName(request, "token");
//            System.out.println("cookie="+cookie.toString());
            if (cookie == null || StringUtils.isEmpty(cookie.getValue())) {
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(433);
                requestContext.setResponse(response);
            } else {
                if (verifyToken(requestContext, request, cookie.getValue().substring(0,cookie.getValue().indexOf("|")))) {
                    /**
                     * 表示不进行路由,其具体意思不太明白,后来经过尝试发现,将其设为false代表的意思是,这个请求最终不会被zuul转发到后端服务器,
                     * 但是如果当前Filter后面还存在其他Filter,那么其他Filter仍然会被调用到,所以一般我们在Filter的shouldFilter方法中,都会通过
                     */
                    requestContext.setSendZuulResponse(false);
                    requestContext.setResponseStatusCode(433);
                    requestContext.setResponse(response);
                    requestContext.setResponseBody("权限不足");
                    requestContext.getResponse().setContentType("text/html;charset=utf-8");

                }else{
                    /**再次判断其拥有的权限是否符合其请求范围开始*/
//                    String username=redisTemplate.opsForValue().get(cookie.getValue().substring(0,cookie.getValue().indexOf("|")))+"";
//                    System.out.println("value="+username);
                    String allquanxian=redisTemplate.opsForValue().get(cookie.getValue().substring(0,cookie.getValue().indexOf("|")))+"";
                    System.out.println("allquanxian="+allquanxian);
                    //取出其权限
                    List<String> list = Arrays.asList(allquanxian.split("|"));
                    //判断是否有该权限
//                    if(){
//
//                    }

                    /**再次判断其拥有的权限是否符合其请求范围结束*/
                }
            }
        }

        return null;

    }
    /**
     * 从Redis中校验token
     */
    private boolean verifyToken(RequestContext cxt, HttpServletRequest request, String token) {
        //判断redis中该用户是否过期
        System.out.println("getrediskey="+token);
        if(redisTemplate.hasKey(token)){
            System.out.println("boolen="+redisTemplate.hasKey(token));
            System.out.println(token+"未过期");
//            System.out.println("tokenvalue list 开始");
            System.out.println("token="+token);
            System.out.println("tokenvalue="+redisTemplate.opsForValue().get(token));
//            String username=redisTemplate.opsForValue().get(token)+"";
//            System.out.println("List="+username);
            return false ;
        }else{
            System.out.println(token+"已过期");
            return true;
        }
    }



}
